<template>
  <div class="app-container">
    <div class="container">
      <!--修改商品标签弹框-->
      <update-label ref="updateLabel"/>
      <!--修改销量弹框-->
      <setDealTimes ref="setDealTimes"/>
      <!--查看二维码弹框-->
      <viewQrcode ref="viewQrcode"/>
      <!--修改库存弹框-->
      <updateInventory ref="updateInventory"/>
      <!--查看商品弹框-->
      <viewCommodity ref="viewCommodity"/>
      <!--工具栏-->
      <div>
        <!-- 图片放大预览功能 -->
        <imgMode ref="imgShow"/>
        <!--标签栏-->
        <el-tabs v-model="activeName" @tab-click="tabClick">
          <el-tab-pane label="全部宝贝" name="1"/>
          <el-tab-pane label="出售中的宝贝" name="2"/>
          <el-tab-pane label="仓库中的宝贝" name="3"/>
        </el-tabs>
        <el-form ref="query" :inline="true" :model="query" size="small" class="demo-form-inline" label-position="right">
          <el-form-item label="分类:" prop="second_variety_id">
            <el-cascader
              v-model="query.variety_id"
              :options="varietyList"
              :props="{ checkStrictly: true }"
              clearable/>
          </el-form-item>
          <el-form-item label="宝贝名称:" prop="name">
            <el-input
              v-model="query.name"
              clearable
              placeholder=""
              style="width:180px;"
              class="filter-item"
              @keyup.enter.native="toQuery"/>
          </el-form-item>
          <el-form-item label="创建时间:" prop="time">
            <el-date-picker
              v-model="query.time"
              :picker-options="pickerOptions2"
              value-format="yyyy-MM-dd HH:mm"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              style="width:360px"/>
          </el-form-item>
          <el-form-item v-if="activeName === '1'" label="宝贝状态:" prop="state">
            <el-select v-model="query.state" clearable placeholder="宝贝状态" class="filter-item" style="width: 180px">
              <el-option v-for="item in stateOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button>
            <el-button size="mini" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!--事件按钮-->
      <div class="operate-container">
        <!-- 批量上架 -->
        <el-button
          :disabled="$refs.table && $refs.table.selection.length === 0"
          class="filter-item"
          size="mini"
          type="primary"
          @click="updowmClick('0')">批量上架
        </el-button>
        <!-- 批量下架 -->
        <el-button
          :disabled="$refs.table && $refs.table.selection.length === 0"
          size="mini"
          plain
          @click="updowmClick('1')">批量下架
        </el-button>
        <!-- 导出（查询） -->
        <el-button
          :loading="downloadLoading"
          plain
          size="mini"
          icon="el-icon-download"
          @click="download('0')">导出（查询）
        </el-button>
        <!-- 导出（勾选） -->
        <el-button
          :loading="downloadLoading"
          :disabled="$refs.table && $refs.table.selection.length === 0"
          plain
          size="mini"
          icon="el-icon-download"
          @click="download('1')"> 导出（勾选）
        </el-button>
      </div>
      <!-- 弹出出素材中心图片弹框 -->
      <div>
        <el-dialog
          :visible.sync="dialogVisible"
          :before-close="handleClose"
          title=""
          width="50%">
          <div class="infinite-list-wrapper" style="overflow:auto;height:500px">
            <ul
              v-infinite-scroll="load"
              class="list"
              infinite-scroll-disabled="disabled">
              <li v-for="(item,index) in materialImageList" id="list-item" :key="index" class="list-item">
                <el-image
                  :src="item.url"
                  :class="{ select: item.active}"
                  style="width: 100px; height: 100px;border-radius:5px"
                  fit="contain"
                  @click="setMaterialImage(item)"
                />
                <div :title="item.desc" class="list-text" style="width: 100px">{{ item.desc }}</div>
              </li>
            </ul>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="updateTagImgClick()">确 定</el-button>
          </span>
        </el-dialog>

      </div>
      <!--表格渲染-->
      <el-table v-loading="loading" ref="table" :data="data" size="small" style="width: 100%;">
        <el-table-column type="selection"/>
        <el-table-column v-if="show" label="商品id" prop="commodity_id" align="center"/>
        <el-table-column label="宝贝" width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <img
              :src="scope.row.link_url ? scope.row.link_url[0].url : ''"
              alt="点击打开"
              class="el-avatar"
              @click="viewImg(scope.row.link_url ? scope.row.link_url[0].url : '')">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="variety_name" align="center"/>
        <el-table-column label="会员价" prop="vip_price" align="center"/>
        <el-table-column label="库存" prop="inventory" align="center"/>
        <el-table-column label="状态" prop="state" width="60" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.state === 0">已上架</div>
            <div v-if="scope.row.state === 1">仓库中</div>
            <div v-if="scope.row.state === 2">自定义时间上架</div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="130" prop="create_date" align="center"/>
        <el-table-column label="操作" align="center" width="270">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="viewClick(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="copyClick(scope.row.commodity_id)">复制</el-button>
            <el-button type="text" size="small" @click="toCommodityDetails(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="inventoryClick(scope.row)">修改库存</el-button>
            <el-popover
              :ref="scope.row.commodity_id"
              placement="top"
              width="180">
              <p>确定删除本条数据吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="$refs[scope.row.commodity_id].doClose()">取消</el-button>
                <el-button :loading="delLoading" type="primary" size="mini" @click="delClick(scope.row.commodity_id)">
                  确定
                </el-button>
              </div>
              <el-button slot="reference" type="text" size="mini">删除</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        :total="total"
        :current-page="page + 1"
        background
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        @size-change="sizeChange"
        @current-change="pageChange"/>
    </div>
  </div>
</template>

<script>
import initData from '@/mixins/initData'
import {
  getCascadeVarietyList,
  updowmCommoditys,
  topCommoditys,
  downloadCommoditys,
  delCommodity,
  createQrcode,
  copyCommodity,
  updateTagImg
} from '@/api/mall/commodity'
import { downloadFile } from '@/utils/index'
import setDealTimes from './setDealTimes'
import viewQrcode from './viewQrcode'
import updateInventory from './updateInventory'
import viewCommodity from './viewCommodity'
import imgMode from './imgMode'
import updateLabel from './updateLabel'
import { getAllMaterialImg } from '@/api/mall/materialCenter'

import timer from '@/api/mall/timer' // 时间对象
import Vue from 'vue'

export default {
  name: 'AllCommodity',
  components: { setDealTimes, viewQrcode, updateInventory, viewCommodity, imgMode, updateLabel },
  mixins: [initData],
  data() {
    return {
      materialImageList: [],
      count: 0,
      pickerOptions2: timer.timer,
      activeName: '1',
      dialogVisible: false,
      tabId: 1,
      show: false,
      varietyList: [],
      downloadLoading: false,
      delLoading: false,
      materialImage: '',
      tagImgType: 0, // 要改变标签图类型 0 封面 1 详情
      query: {
        is_had_query: true, // 是否存在查询条件,通过此字段判断是否存在了全局
        variety_id: '',
        name: '',
        state: '',
        starttime: '',
        endtime: '',
        price: '',
        sale: '',
        supplier_name: '',
        time: '',
        most_spec: ''
      },
      stateOptions: [
        { key: '', display_name: '全部' },
        { key: '0', display_name: '已上架' },
        { key: '1', display_name: '仓库中' }
      ],
      priceOptions: [
        { key: 'ASC', display_name: '由低到高' },
        { key: 'DESC', display_name: '由高到低' }
      ],
      saleOptions: [
        { key: 'ASC', display_name: '由低到高' },
        { key: 'DESC', display_name: '由高到低' }
      ],
      mostSpecOptions: [
        { key: '', display_name: '' },
        { key: '0', display_name: '单规格/无规格' },
        { key: '1', display_name: '多规格' }
      ]
    }
  },
  created() {
    // 先从全局获取查询条件，若有，直接取此查询条件.为从别的页面跳转至本页面之后根据查询条件进行查询
    this.query = this.$commodityListQuery.is_had_query ? this.$commodityListQuery : this.query
    // 先全局挂载拿到商品列表的分页
    this.page = this.$commodityListParams.page ? this.$commodityListParams.page : this.page
    this.size = this.$commodityListParams.size ? this.$commodityListParams.size : this.size
    this.tabId = this.$commodityListParams.tabId ? this.$commodityListParams.tabId : this.tabId
    // 获取商品分类
    getCascadeVarietyList().then(res => {
      this.varietyList = res.content
    })
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    beforeInit() {
      this.url = 'api/commodity-list'
      const sort = 'create_date,desc'
      this.params = { page: this.page, size: this.size, sort: sort, tabId: this.tabId }
      // 查询条件组装为实体
      this.querySetObject()
      // 全局挂载商品分页
      Vue.prototype.$commodityListParams = this.params
      return true
    },
    querySetObject() {
      const query = this.query
      const name = query.name
      const variety_id = query.variety_id
      const state = query.state
      const supplier_name = query.supplier_name
      const price = query.price
      const sale = query.sale
      const time = query.time
      const most_spec = query.most_spec
      if (time !== '' && time !== undefined) {
        this.params['time'] = time.join('~')
      }
      if (name && name !== '' && time !== null) {
        this.params['name'] = name
      }
      if (variety_id && variety_id !== '' && variety_id !== null) {
        this.params['variety_id'] = variety_id.join(',')
      }
      if (state && state !== '' && state !== null) {
        this.params['state'] = state
      }
      if (supplier_name) {
        this.params['supplier_name'] = supplier_name
      }
      if (price && price !== '' && price !== null) {
        this.params['price'] = price
      }
      if (sale && sale !== '' && sale !== null) {
        this.params['sale'] = sale
      }
      if (most_spec && most_spec !== '' && most_spec !== null) {
        this.params['most_spec'] = most_spec
      }
      // 每次查询之后，商品列表最新的查询条件挂载全局，为从别的页面跳转至本页面之后根据查询条件进行查询
      Vue.prototype.$commodityListQuery = query
    },
    // 切换tab
    tabClick(tab, event) {
      this.tabId = tab.name
      this.page = 0
      this.$nextTick(() => {
        this.init()
      })
    },
    // 修改标签
    updateLabel() {
      const dataSelect = this.$refs.table.selection
      const commodity_ids = []
      for (let i = 0; i < dataSelect.length; i++) {
        commodity_ids.push(dataSelect[i].commodity_id)
      }
      // 第一个商品的标签值，因为只有选中商品时才会进入此方法，所以不作数据空判断
      const label = dataSelect[0].label_brand_ids
      this.$refs.updateLabel.dialog = true
      this.$refs.updateLabel.form.commodity_ids = commodity_ids
      // 调用子组件的方法，把第一个商品的标签传进，作为默认选中值
      this.$refs.updateLabel.setChecked(label)
    },
    // 修改销量
    dealTimesClick() {
      const dataSelect = this.$refs.table.selection
      const commodity_ids = []
      for (let i = 0; i < dataSelect.length; i++) {
        commodity_ids.push(dataSelect[i].commodity_id)
      }
      this.$refs.setDealTimes.dialog = true
      this.$refs.setDealTimes.form.commodity_ids = commodity_ids
    },
    viewImg(url) {
      // 图片放大预览
      this.$refs.imgShow.dialog = true
      this.$refs.imgShow.imgUrl = url
    },
    // 上架，下架商品
    updowmClick(type) {
      const dataSelect = this.$refs.table.selection
      const commodity_ids = []
      for (let i = 0; i < dataSelect.length; i++) {
        commodity_ids.push(dataSelect[i].commodity_id)
      }
      const data = { 'commodity_ids': commodity_ids, 'type': type }
      updowmCommoditys(data).then(res => {
        this.doback(res)
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    // 置顶,取消置顶商品
    topCommodityClick(type) {
      const dataSelect = this.$refs.table.selection
      const commodity_ids = []
      for (let i = 0; i < dataSelect.length; i++) {
        commodity_ids.push(dataSelect[i].commodity_id)
      }
      const data = { 'commodity_ids': commodity_ids, 'type': type }
      topCommoditys(data).then(res => {
        this.doback(res)
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    // 导出
    download(type) {
      // 从新获取查询条件
      this.querySetObject()
      this.downloadLoading = true
      let data = {}
      if (type === '0') {
        // 导出查询
        data = this.params
      } else {
        // 导出勾选
        const dataSelect = this.$refs.table.selection
        const commodity_ids = []
        for (let i = 0; i < dataSelect.length; i++) {
          commodity_ids.push(dataSelect[i].commodity_id)
        }
        data = { 'commodity_ids': commodity_ids }
      }
      downloadCommoditys(data).then(result => {
        downloadFile(result, '商品列表', 'xlsx')
        this.downloadLoading = false
      }).catch((err) => {
        console.log(err.response.data.message)
        this.downloadLoading = false
      })
    },
    // 删除单个商品
    delClick(commodity_id) {
      // 删除
      this.delLoading = true
      const commodityId = { 'commodity_id': commodity_id }
      delCommodity(commodityId).then(res => {
        this.delLoading = false
        this.$refs[commodity_id].doClose()
        if (res.result) {
          this.$notify({
            title: res.msg,
            type: 'success',
            duration: 2500
          })
        } else {
          this.$notify({
            title: res.msg,
            type: 'error',
            duration: 2500
          })
        }
        this.init()
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    // 查看，生成二维码
    qrcodeClick(commodity_id, qrcode_url) {
      if (qrcode_url === null || qrcode_url === undefined) {
        // 先生成二维码
        const data = { 'proid': commodity_id }
        createQrcode(data).then(res => {
          qrcode_url = res.content
          this.$refs.viewQrcode.dialog = true
          this.$refs.viewQrcode.form.qrcode_url = qrcode_url
        })
      } else {
        this.$refs.viewQrcode.dialog = true
        this.$refs.viewQrcode.form.qrcode_url = qrcode_url
      }
    },
    // 修改库存
    inventoryClick(info) {
      this.$refs.updateInventory.dialog = true
      const json = Object.assign({}, (info))
      this.$refs.updateInventory.form.commodity_id = json.commodity_id
      this.$refs.updateInventory.form.info = json
      this.$refs.updateInventory.form.oldInfo = JSON.parse(JSON.stringify(info))
    },
    // 查看单个商品信息
    viewClick(commodity) {
      this.$refs.viewCommodity.dialog = true
      this.$refs.viewCommodity.commodity = commodity
    },
    // 复制单个商品信息
    copyClick(commodity_id) {
      const parms = { commodity_id: commodity_id }
      copyCommodity(parms).then(res => {
        if (res.result) {
          // 商品分类
          const classifyIdList = [res.content.variety_id]
          if (res.content.second_variety_id && res.content.second_variety_id.length > 0 && res.content.second_variety_id !== '0') {
            classifyIdList.push(res.content.second_variety_id)
          }
          // 数组转字串，便于页面解析
          const query = { 'classify_id': classifyIdList.join(','), 'commodity_id': res.content.commodity_id }
          this.$router.push({ path: '/commodity/details', query: query })
        }
      })
    },
    // 编辑商品跳转商品详情页
    toCommodityDetails(row) {
      const classifyIdList = [row.variety_id]
      if (row.second_variety_id && row.second_variety_id.length > 0 && row.second_variety_id !== '0') {
        classifyIdList.push(row.second_variety_id)
      }
      // 数组转字串，便于页面解析
      const query = { 'classify_id': classifyIdList.join(','), 'commodity_id': row.commodity_id }
      this.$router.push({ path: '/commodity/details', query: query })
    },
    doback(res) {
      if (res) {
        // 执行成功
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
      } else {
        // 系统不会报错，但是会有提示语，告知如何操作
        this.$notify({
          title: '修改失败',
          type: 'error',
          duration: 2500
        })
      }
      this.init()
    },
    // 重置查询条件
    resetQuery() {
      this.$refs['query'].resetFields()
      this.query = {
        time: ''
      }
      this.queryOrderDate = ['', '']
      this.init()
    },
    // 打开封面标签
    openSetTagImage(type) {
      this.tagImgType = type
      getAllMaterialImg().then(res => {
        var data = []
        if (res.materials) {
          data = res.materials.map(item => {
            item.active = false
            return item
          })
          this.materialImageList = data
        }
      }).catch(err => {
        console.log(err.response.data.message)
      })
      this.dialogVisible = true
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    load() {
      this.count += 2
    },
    setMaterialImage(material) {
      const productSelected = this.materialImageList.filter(item => item.active === true ? item : 0)
      console.log(productSelected)
      if (productSelected.length !== 0) {
        const selectIndex = this.materialImageList.indexOf(productSelected[0])
        this.materialImageList[selectIndex].active = !this.materialImageList[selectIndex].active
      }

      const index = this.materialImageList.indexOf(material)
      this.materialImageList[index].active = !this.materialImageList[index].active
      if (material) {
        this.materialImage = material
      }
    },
    updateTagImgClick() {
      if (!this.materialImage || !this.materialImage.url) {
        this.$confirm('请选择图片', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
          return false
        })
      }
      const dataSelect = this.$refs.table.selection
      const commodity_ids = []
      for (let i = 0; i < dataSelect.length; i++) {
        commodity_ids.push(dataSelect[i].commodity_id)
      }
      const data = { 'commodity_ids': commodity_ids }
      if (this.tagImgType === 0) {
        data['cover_tag_img'] = this.materialImage.url
      } else {
        data['detail_tag_img'] = this.materialImage.url
      }
      updateTagImg(data).then(res => {
        if (res.result) {
          this.dialogVisible = false
          // // 执行成功
          this.$notify({
            title: '修改成功',
            type: 'success',
            duration: 2500
          })
          // // 刷新页面
          this.init()
        } else {
          this.$confirm(res.msg, '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          }).then(() => {
            return false
          })
        }
      }).catch(err => {
        this.dialogVisible = false
        console.log(err.response.data.message)
      })
    }
  }
}
</script>

<style scoped>
.list{
  display: flex;
  flex-wrap: wrap;
}
#list-item{
  width: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;
  list-style-type:none;
  text-align: center;
  margin: 10px 0;

}
.list-text{
   width: 180px;
   white-space:nowrap;
   overflow:hidden;
   text-overflow:ellipsis;
}
.select{
  border:2px solid #1682e6
}
</style>
